package cn.lyjuan.archetypes.bms.web.exception;


import cn.lyjuan.archetypes.bms.web.bean.vo.BaseResp;
import cn.lyjuan.archetypes.bms.web.util.AppUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.nio.file.AccessDeniedException;

/**
 * Created by ly on 2015/1/11.
 */
@ControllerAdvice
@ResponseBody
public class ExceptionResolver
{
    private static Logger log = LogManager.getLogger(ExceptionResolver.class.getName());

    @ExceptionHandler(Throwable.class)
    public ModelAndView doResolveException(Exception e)
    {
        logExce(e);// 打印日志

        boolean isAjax = AppUtils.isAjax();// 是否为 ajax 请求

        return isAjax ? ajaxExce(e) : pageExce(e);
    }

    /**
     * 后台 ajax 异常，后台会将所有的错误状态码转换为 {@code MgRetCode.ERR}
     * @param e
     * @return
     */
    public ModelAndView ajaxExce(Exception e)
    {
        String json = null;
        String msg  = null;

        if (e instanceof AccessDeniedException)
        {
            msg = "没有足够的权限";
        }
        else if (e instanceof BmsException)
        {
            BmsException infoE = (BmsException) e;

            msg = infoE.getMessage();
        } else
            msg = "系统繁忙";

        BaseResp resp = BaseResp.resp(AppCode.ERR, msg);

        // 返回 JSON 数据
        AppUtils.respJson(resp);

        return new ModelAndView();
    }

    /**
     * 后台 page 异常
     * @param e
     * @return
     */
    public ModelAndView pageExce(Exception e)
    {
        String msg = null;

        if (e instanceof AccessDeniedException)
        {
            msg = "没有足够的权限";
        }
        else if (e instanceof BmsException)
        {
            BmsException infoE = (BmsException) e;

            msg = infoE.getMessage();
        }

        return new ModelAndView("/500", AppCode.MSG_NAME, msg);
    }

    /**
     * 打印错误信息
     * @param e
     */
    private void logExce(Exception e)
    {
        if (e instanceof AccessDeniedException)
        {
            log.warn("权限不足", e);
        }
        else if (e instanceof BmsException)
        {
            BmsException info = (BmsException) e;

            log.error("错误信息 " + info.getMessage());
        } else
        {
            log.error("系统异常", e);
        }
    }
}
